<template>
<el-card class="querycondition-card" shadow="never">
<div>
    <el-form ref="customquery" :model="queryParam" id="componentQuery" :inline="true" label-width="180px" @keyup.enter.native.prevent="queryClick">
    <template v-if="items&&items.length>0" v-for="item in items">
        <el-form-item :label="_$Z[item.label]" v-if="item.elType==='node'" :key="item.label">
          <custom-node-new v-model="queryParam[item.id]" :supportType="item.supportType"></custom-node-new>
        </el-form-item>

        <!-- org -->
        <el-form-item :label="_$Z[item.label]" v-if="item.elType==='org'" :key="item.label">
          <org-combox v-model="queryParam[item.id]" :value="item.value"></org-combox>
        </el-form-item>

        <el-form-item :prop="item.id" :rules="filter_rules(item.validator ? item.validator : {spChar:true,length:[-1,50]})" :label="_$Z[item.label]" v-if="item.elType==='input'" :key="item.label">
          <el-input prefix-icon="el-icon-search" :type="item.id" :disabled="item.disabled"
                    v-model.trim="queryParam[item.id]" style="margin-right:2%">
          </el-input>
        </el-form-item>
      
        <el-form-item :label="_$Z[item.label]" v-if="item.elType==='select'" :key="item.label">
          <custom-combox v-model="queryParam[item.id]" :code-type="item.codeType" :is-all="item.isAll" 
          :disabled="item.disabled"
          :onlyNeedValues="item.onlyNeedValues?item.onlyNeedValues:[]"
                          @input="(()=>handChange(queryParam[item.id],item.method?item.method:null))">
          </custom-combox>
        </el-form-item>

        <el-form-item :label="_$Z[item.label]" v-if="item.elType==='linkSelect'" :key="item.label">
          <custom-combox v-model="queryParam[item.id]" :code-type="item.codeType" 
                        :disabled="item.disabled"
                        :is-all="item.isAll" 
                        :onlyNeedValues="item.onlyNeedValues?item.onlyNeedValues:[]"
                        @input="(()=>handChange(queryParam[item.id],item.method?item.method:null))">
          </custom-combox>
        </el-form-item>
        
        <el-form-item :label="_$Z[item.label]" v-if="item.elType==='groupSelect'" :key="item.label">
          <group-combox :ref="item.id" v-model="queryParam[item.id]" :is-all="item.isAll" :url="item.url" :queryparam="item.queryparam"></group-combox>
        </el-form-item>
        <el-form-item :label="_$Z[item.label]" v-if="item.elType==='defSelect'" :key="item.label">
          <def-combox v-model="queryParam[item.id]" :is-all="item.isAll" :url="item.url" :queryparam="item.queryparam"
                         @input="(()=>handChange(queryParam[item.id],item.method?item.method:null))">
          </def-combox>
        </el-form-item>

        <el-form-item :label="_$Z[item.label]" v-if="item.elType==='multiSelect'" :key="item.label">
          <multiple-combox v-model="queryParam[item.id]"
                         :code-type="item.codeType"
                         :is-all="item.isAll">
          </multiple-combox>
        </el-form-item>
        <el-form-item :label="_$Z[item.label]" v-if="item.elType==='ndatetime'" :key="item.label">         
              <el-date-picker width="100%" v-model="queryParam[item.id]"
                            type="datetimerange" 
                            format="yyyy-MM-dd HH:mm:ss"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            :start-placeholder="_$Z['startTime']"
                            :end-placeholder="_$Z['endTime']"
                            :default-time="['00:00:00','00:00:00']"                         
                            :picker-options="pickerOptions"
                            :clearable="false"
                            :editable="false">
              </el-date-picker>        
        </el-form-item>

        <el-form-item :label="_$Z[item.label]" v-if="item.elType==='datetime'" :key="item.label">
         
            <el-date-picker v-model="queryParam[item.id]"
                            type="datetime"
                            :placeholder="_$Z['dateTime']"
                            format="yyyy-MM-dd HH:mm:ss"
                            value-format="yyyy-MM-dd HH:mm:ss"                         
                            :default-time="['00:00:00','00:00:00']"
                            :clearable="false"
                            :editable="false">
            </el-date-picker>          
        </el-form-item>

        <el-form-item :label="_$Z[item.label]" v-if="item.elType==='date'" :key="item.label">
         
            <el-date-picker v-model="queryParam[item.id]"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            :placeholder="_$Z['dateTime']"
                            :picker-options="pickerOptionsNoshortCuts"
                            :clearable="false"
                            :editable="false">
            </el-date-picker>    
        </el-form-item>

        <el-form-item :label="_$Z[item.label]" v-if="item.elType==='ndate'" :key="item.label">
      
            <el-date-picker v-model="queryParam[item.id]"
                            type="daterange"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            :start-placeholder="_$Z['startTime']"
                            :end-placeholder="_$Z['endTime']"                          
                            :picker-options="pickerOptions"
                            :clearable="false"
                            :editable="false">
            </el-date-picker>   

        </el-form-item>

        <el-form-item :label="_$Z[item.label]" v-if="item.elType==='month'" :key="item.label">
         
            <el-date-picker v-model="queryParam[item.id]"
                            type="month"
                            format="yyyy-MM"
                            value-format="yyyy-MM"
                            :clearable="false"
                            :editable="false">
            </el-date-picker>    

        </el-form-item>
        <el-form-item :label="_$Z[item.label]" v-if="item.elType==='year'" :key="item.label">
       
            <el-date-picker v-model="queryParam[item.id]"
                            type="year"
                            format="yyyy"
                            value-format="yyyy"
                            :clearable="false"
                            :editable="false">
            </el-date-picker>

        </el-form-item>
        <el-form-item :label="_$Z[item.label]" v-if="item.elType==='radioDate'" :key="item.label">
          <radio-datepicker  :items="item.radiotypes" :isrange="item.isrange" :rangeSeparator="item.rangeSeparator" v-model="queryParam[item.id]">
          </radio-datepicker>
        </el-form-item>

        <el-form-item :label="_$Z[item.label]" v-if="item.elType==='contrastDate'" :key="item.label">
          <time-comparison  :items="item.radiotypes" :isrange="item.isrange" v-model="queryParam[item.id]">
          </time-comparison>
        </el-form-item>
		
    </template>
    <el-form-item v-if="items.length < 3" style="margin:0 10px;float: right;">
      <custom-btn btnType="query"
                  :label="_$Z['query']"
                  @btn-click="queryClick"
                  style="margin:0 4px;float: right;">
      </custom-btn>
    </el-form-item>
  </el-form>
  <el-row v-if="items.length >= 3">
    <el-col :span="24" class="bg-purple">
      <custom-btn btnType="query"
                  :label="_$Z['query']"
                  @btn-click="queryClick"
                  style="position: relative; left: 92%;">
      </custom-btn>
    </el-col>
  </el-row>
</div>
</el-card>
</template>

<script>
import CustomCombox from '@/views/platform/components/selector/customCombox'
import GroupCombox from '@/views/platform/components/selector/groupCombox'
import customNodeNew from '@/views/platform/components/common/customNodeNew'
import orgCombox from '@/views/platform/components/common/orgCombox'
import RadioDatepicker from '@/views/platform/components/datePicker/radioDatepicker'
import defCombox from '@/views/platform/components/selector/defCombox'
import multipleCombox from '@/views/platform/components/selector/multipleCombox'
import timeComparison from '@/views/platform/components/datePicker/doubleRadioDatepicker'
import { parseTime } from '@/utils/index'

export default {
  name: 'CustomQuery',
  data() {
    const i18Keys = ['query', 'startTime', 'endTime', 'today', 'yesterday', 'weekAgo', 'monthAgo', '130-A_CONSUMER-TRADE_CODE']
    this.items.forEach(element => {
      i18Keys.push(element.label)
    })

    return {
      queryParam: {},
      i18Keys: i18Keys,
      pickerOptions: {
        disabledDate(value) {
          const today = new Date()
          return value >= today
        },
        shortcuts: [{
          text: this.$t('datePicker.yesterday'),
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setDate(start.getDate() - 1)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: this.$t('datePicker.weekAgo'),
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setDate(start.getDate() - 7)

            picker.$emit('pick', [start, end])
          }
        }, {
          text: this.$t('datePicker.monthAgo'),
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 1)

            picker.$emit('pick', [start, end])
          }
        }]
      },
      pickerOptionsNoshortCuts: {
        disabledDate(value) {
          const today = new Date()
          return value >= today
        }
      },
      supportType: ['ndatetime', 'datetime', 'ndate', 'date', 'month', 'year'],
      supportTypeFormat: ['{y}-{m}-{d} {h}:{i}:{s}', '{y}-{m}-{d} {h}:{i}:{s}', '{y}-{m}-{d}', '{y}-{m}-{d}', '{y}-{m}', '{y}'],
      radioType: ['day', 'month', 'year'],
      radioDateFormat: ['{y}-{m}-{d}', '{y}-{m}', '{y}']
    }
  },
  components: { CustomCombox, GroupCombox, RadioDatepicker, customNodeNew, defCombox, multipleCombox, timeComparison, orgCombox },
  props: {
    defaultValue: { // 设置默认值,格式为：{this.items.id:default}
      type: Object
    },
    items: {
      type: Array,
      required: true,
      validator: function(value) {
        let result = true
        value.forEach(element => {
          if (element.label) {
            result = true
          }
          if (element.elType && ['input', 'ndate', 'date', 'select', 'ndatetime', 'datetime', 'year', 'month'].indexOf(element.elType) !== -1) {
            if (element.elType === 'select') {
              if (element.codeType) {
                result = true
              }
            }
          } else {
            return false
          }
          if (element.elType === 'radioDate') {
            if (element.radiotypes instanceof Array) {
              result = true
            } else if (!element.radiotypes) {
              element.radiotypes = ['year', 'month']
              result = true
            } else {
              return false
            }
            if (!element.daysCount) {
              element.daysCount = 7
              result = true
            }
            if (element.isrange) {
              result = true
            } else {
              return false
            }
            if (!result) {
              return false
            }
          }
        })
        return result
      }
    }
  },
  methods: {
    queryClick() {
      this.$refs.customquery.validate((valid) => {
        if (valid) {
          const queryParamTmp = this.queryParam
          this.$emit('query', queryParamTmp)
        }
      })
    },
    pick(date) {
      this.items.forEach(value => {
        if (value.elType && ['ndate', 'date', 'ndatetime', 'datetime', 'year', 'month'].indexOf(value.elType) !== -1) {
          this.queryParam[value.id] = date
        }
      })
    },
    handChange(val, callback) {
      if (callback) {
        callback(val)
      }
    },
    setDefaultValue() {
      const queryParamTmp = {}
      if (this.defaultValue) {
        this.items.forEach(element => {
          if (!this.defaultValue[element.id]) {
            return true
          }
          if (this.supportType.indexOf(element.elType) >= 0) { // date日期格式化
            const format = this.supportTypeFormat[this.supportType.indexOf(element.elType)]
            if (this.defaultValue[element.id] instanceof Array) {
              const newValue = []
              this.defaultValue[element.id].forEach(element1 => {
                newValue.push(parseTime(element1, format))
              })
              queryParamTmp[element.id] = newValue
            } else if (this.defaultValue[element.id] instanceof Date) {
              queryParamTmp[element.id] = parseTime(this.defaultValue[element.id], format)
            }
          } else if (element.elType === 'radioDate') {
            // 单选联动日期选择控件日期格式化
            const newValue = {}
            let format = '{y}-{m}-{d}'
            if (this.defaultValue[element.id]) {
              const radio = this.defaultValue[element.id].radio
              const start = this.defaultValue[element.id].start
              const end = this.defaultValue[element.id].end
              if (radio) {
                format = this.radioDateFormat[this.radioType.indexOf(radio)]
                newValue.radio = this.defaultValue[element.id].radio
                if (start instanceof Date) {
                  newValue.start = parseTime(start, format)
                } else {
                  newValue.start = start
                }
                if (end instanceof Date) {
                  newValue.end = parseTime(end, format)
                } else {
                  newValue.end = end
                }
              }
              queryParamTmp[element.id] = newValue
            }
          } else if (element.elType === 'contrastDate') {
            // 单选联动日期选择控件日期格式化
            const newValue = {}
            let format = '{y}-{m}-{d}'
            if (this.defaultValue[element.id]) {
              const radio = this.defaultValue[element.id].radio
              const start1 = this.defaultValue[element.id].start1
              const end1 = this.defaultValue[element.id].end1
              const start2 = this.defaultValue[element.id].start2
              const end2 = this.defaultValue[element.id].end2
              if (radio) {
                format = this.radioDateFormat[this.radioType.indexOf(radio)]
                newValue.radio = this.defaultValue[element.id].radio
                if ((start1, start2) instanceof Date) {
                  newValue.start1 = parseTime(start1, format)
                  newValue.start2 = parseTime(start2, format)
                } else {
                  newValue.start1 = start1
                  newValue.start2 = start2
                }
                if ((end1, end2) instanceof Date) {
                  newValue.end1 = parseTime(end1, format)
                  newValue.end2 = parseTime(end2, format)
                } else {
                  newValue.end1 = end1
                  newValue.end2 = end2
                }
              }
              queryParamTmp[element.id] = newValue
            }
          } else if (element.elType === 'multiSelect') {
            queryParamTmp[element.id] = this.defaultValue[element.id] ? this.defaultValue[element.id] : []
          } else {
            queryParamTmp[element.id] = this.defaultValue[element.id] ? this.defaultValue[element.id] : ''
          }
        })
        this.queryParam = queryParamTmp
      }
    },
    changeQueryItem(value) {
      this.$emit('changeQueryItem', value)
    }
  },
  created() {
    if (this.defaultValue) {
      this.setDefaultValue()
    }
  },
  watch: {
    // 实时监测组件中对象的默认值，并更新
    defaultValue: {
      handler: function() {
        this.setDefaultValue()
      },
      deep: true
    },
    items(value) {
      this.setDefaultValue()
      value.forEach(element => {
        this.i18Keys.push(element.label)
      })
    },
    queryParam: {
      handler: function() { // 报文查询功能涉及节点选择后，动态改变查询条件值
        this.items.forEach(element => {
          if (element.elType === 'node') {
            if (this.queryParam.node) {
              if (this.queryParam.node.objectType === 'meter' || this.queryParam.node.objectType === 'endDevice') {
                this.changeQueryItem(this.queryParam)
              }
            }
          }
        })
      },
      deep: true
    }
  }
}
</script>